package com.medical.manage.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.medical.common.core.domain.Result;
import com.medical.common.core.web.controller.BaseController;
import com.medical.common.core.web.page.TableDataInfo;
import com.medical.common.log.annotation.Log;
import com.medical.common.log.enums.BusinessType;
import com.medical.common.security.annotation.RequiresPermissions;
import com.medical.common.security.utils.SecurityUtils;
import com.medical.manage.domain.*;
import com.medical.manage.domain.vo.ArticleVo;
import com.medical.manage.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;


@RestController
@RequestMapping("article")
public class ArticleController extends BaseController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private AdviceService adviceService;
    @Autowired
    private CommentsService commentsService;
    @Autowired
    private CollectRecordingService collectRecordingService;
//    @Autowired
//    private BrowseService browseService;


    /**
     * 案例展示
     * @return
     */
    @GetMapping("/getDemoArticle")
    public Result<TableDataInfo> getDemoArticle(){
        return getDataTable(articleService.getDemoArticle());
    }

    /**
     * 案例文章列表详情
     * @return
     */
    @GetMapping("/getArticleDetail/{id}")
    public Result getArticleList(@PathVariable Integer id){
        return articleService.getArticleDetail(id);
    }

//    /**
//     * 统计浏览数量
//     * @param id
//     * @return
//     */
//    @GetMapping("/countBrowseNum/{id}")
//    public Result countBrowseNum(@PathVariable Integer id){
//        return browseService.countBrowseNum(id);
//    }

    /**
     * 发布文章
     * @param articleVo
     * @return
     */
    @PostMapping("/publishArticle")
    public Result publishArticle(@RequestBody ArticleVo articleVo){
        return articleService.publishArticle(articleVo);
    }

    /**
     * 保存到草稿箱
     * @param articleVo
     * @return
     */
    @PostMapping("/saveDraft")
    public void saveDraft(@RequestBody ArticleVo articleVo){
        articleService.saveDraft(articleVo);
    }

    /**
     * 草稿箱列表
     * @return
     */
    @GetMapping("/getDraft")
    public Result<List<Article>> getDraft(){
        return articleService.getDraft();
    }

    /**
     * 我创作的文章列表
     * @return
     */
    @GetMapping("/getMyCreation")
    public Result<List<Article>> getMyCreation(){
        return articleService.getMyCreation();
    }

    /**
     * 查看创作文章详情
     * @return
     */
    @GetMapping("/getCreateArticleDetail/{id}")
    public Result getCreateArticleDetail(@PathVariable Integer id){
        return articleService.getCreateArticleDetail(id);
    }

    /**
     * 推荐阅读文章
     * @param id
     * @return
     */
    @GetMapping("/recommendReadArticle/{id}")
    public Result<List<ArticleVo>> recommendReadArticle(@PathVariable Integer id){
        return articleService.recommendReadArticle(id);
    }

    /**
     * 删除文章
     * @param ids
     */
    @RequiresPermissions("manage:patient:remove")
    @Log(title = "删除文章",businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public void remove(@PathVariable Long[] ids){
        //将Long[]数组转为List<Long>集合
        List<Long> list = Arrays.asList(ids);
        articleService.removeBatchByIds(list);
    }

    /**
     * 用户信息（用户发布的病友圈）
     * @param userId
     * @return
     */
    @GetMapping("/getPatientInfo/{publisher}")
    public List<Article> getPatientInfo(@PathVariable String userId ){
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getUserId, userId);
        List<Article> list = articleService.list(queryWrapper);
        return list;
    }

    /**
     * 写建议
     * @param advice
     * @return
     */
    @PostMapping("/writeComment")
    public Result writeComment(@RequestBody Advice advice){
        //修改建议数量
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("article_id",advice.getArticleId());
        wrapper.setSql("advice_num=advice_num+1");
        articleService.update(wrapper);
        //保存建议内容
        adviceService.save(advice);
        return Result.success(wrapper);
    }

    /**
     * 查询评论
     * @return
     */
    @GetMapping("/getComment/{id}")
    public Result getComment(@PathVariable Integer id){
        return commentsService.getComment(id);
    }

    /**
     * 发布评论
     * @param comments
     */
    @PostMapping("/publishComment")
    public void publishComment(@RequestBody Comments comments){
        commentsService.publishComment(comments);
    }


    /**
     * 收藏
     * @param articleId
     * @return
     */
    @PostMapping("/updateCollect/{articleId}")
    public Result updateCollect(@PathVariable Integer articleId){
        /*LambdaQueryWrapper<CollectionRecording> wrapper = new LambdaQueryWrapper<>();*/
        //获取用户id
        Long userId = SecurityUtils.getUserId();
        /*//判断用户是否已经收藏过 一个用户只能收藏一次
        wrapper.and(Collect->wrapper.eq(CollectionRecording::getUserId,userId).eq(CollectionRecording::getPatientId,patientId));
        List<CollectionRecording> list = collectRecordingService.getBaseMapper().selectList(wrapper);
        if(list.size()>1){
            return Result.error("一个用户只能收藏一次");
        }*/
        //添加到我的收藏
        CollectionRecording recording = new CollectionRecording();
        recording.setArticleId(articleId);
        recording.setUserId(userId);
        collectRecordingService.save(recording);
        //统计收藏数量 返回给前端  (聚合函数查询)
        QueryWrapper<CollectionRecording> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("count(*) as count,patient_id");
        queryWrapper.groupBy("patient_id");
        //判断patientId是否为空
        if (articleId != null) {
            queryWrapper.having("article_id={0}",articleId);// 动态添加 having 条件
        }
        Map<String, Object> map = collectRecordingService.getMap(queryWrapper);
        return Result.success(map);
    }




}
